import logging
import os
import wsgiref.handlers
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from models import AppUser, Bookmark

class AddBookmarkHandler(webapp.RequestHandler):
	def get(self):
		path = os.path.join(os.path.dirname(__file__), 'base.html')
		self.response.out.write(template.render(path, {}))
		return
		
	def post(self):
		name = self.request.get("name")
		url = self.request.get("url")
		query = AppUser.all().filter('user =', users.get_current_user())
		try:
			app_user = query.fetch(1)[0]
			bookmarks = Bookmark.all().filter('app_user =', app_user).fetch(1000)
		except:
			path = os.path.join(os.path.dirname(__file__), 'base.html')
			data = {'messages': ['Could not get your app_user']}
			self.response.out.write(template.render(path, data))
			return
			
		if 'xmts.us' in url:
			path = os.path.join(os.path.dirname(__file__), 'view_me.html')
			data = {'messages': ['Recursive bookmarks are not appreciated.'], 'app_user':app_user, 'bookmarks':bookmarks}
			self.response.out.write(template.render(path, data))
			return
		
		query = Bookmark.all().filter("name =", name).filter("app_user =", app_user)
		
		try:
			bookmark = query.fetch(1)[0]
			
			old_url = bookmark.url
			bookmark.url = db.Link(url)
			bookmark.hits = 0
			bookmark.put()
			logging.info("Bookmark edited: name=%s, was_url=%s, new_url=%s" % (name, old_url, url))
			self.redirect('/x')
			return
		except:
			# bookmark with that name does not exist for this user
			try:
				bookmark = Bookmark(app_user=app_user, name=name, url=db.Link(url))
				bookmark.put()
				logging.info("Bookmark added: name=%s, url=%s" % (name, url))
				self.redirect('/x')
				return
			except:
				path = os.path.join(os.path.dirname(__file__), 'view_me.html')
				data = {'messages': ['The name or URL were invalid'], 'app_user':app_user, 'bookmarks':bookmarks}
				self.response.out.write(template.render(path, data))
				return	
def main():
	app = webapp.WSGIApplication([(r'.*', AddBookmarkHandler)], debug=True)
	wsgiref.handlers.CGIHandler().run(app)
	
if __name__ == "__main__":
	main()